package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.exception.ValidUtil;
import cn.itsource.hrm.service.IImageVerifyCodeService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ImageVerifyCodeServiceImpl implements IImageVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult getCodeByKey(String imageCodeKey) {
        ValidUtil.assertNotNull(imageCodeKey,"非法操作，请重试！");
        //1 产生字符串验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2 把字符串验证码写入图片
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            VerifyCodeUtils.outputImage(140, 40, data, code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3 对图片进行base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String imgBase64Data = encoder.encode(data.toByteArray());
        //4 把字符串验证码存放到redis
        long expireTime = 3;
        redisTemplate.opsForValue().set(imageCodeKey,code,expireTime, TimeUnit.MINUTES);
        //5 返回base64编码数据
        return AjaxResult.me().setResultObj(imgBase64Data);
    }

    @Override
    public AjaxResult verifyCode(Map<String, String> params) {
        //获取key和code
        String imageCodeKey = params.get("imageCodeKey");
        String imageCode = params.get("imageCode");
        //通过key从redis获取rediscode
        String redisCode= (String) redisTemplate.opsForValue().get(imageCodeKey);
        //两个进行比较
        return imageCode.equalsIgnoreCase(redisCode)?AjaxResult.me()
                :AjaxResult.me().setSuccess(false).setMessage("图片验证码不正确!");
    }
}
